import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './plugins/element.js'
import './assets/css/global.css'
import axios from 'axios'
import rules from './plugins/verify'
import Element from 'element-ui'

Vue.prototype.$rules = rules;
const baseUrl = window.configInfo.address;
Vue.prototype.$baseUrl = baseUrl;
/*配置请求的根路径*/
axios.defaults.baseURL=baseUrl;
Vue.config.productionTip = false;
Vue.prototype.$http = axios;

let loadingInstance;
let loadingCount = 0;
function startLoading() {    //使用Element loading-start 方法
    loadingInstance = Element.Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

function showLoading() {
    if (loadingCount === 0 ){
        startLoading();
    }
    loadingCount++;
}
function endLoading() {    //使用Element loading-close 方法
    if (loadingCount > 0 ){
        loadingInstance.close();
        loadingCount--;
    }
}



axios.interceptors.request.use(
    config => {
        showLoading();
        /*判断token是否存在*/
        if (sessionStorage.getItem("authorization")){
            config.headers['authorization'] = sessionStorage.getItem("authorization");
        }
        if (sessionStorage.getItem("userId")){
            config.headers['userId'] = sessionStorage.getItem("userId");
        }
        return config;
    },
    error => {
        router.push({
            name: '404错误页面'
        });
        return Promise.reject(error);
    }
);
axios.interceptors.response.use(response => {
    let path = location.pathname;
    let data = response.data;
    if (path !== "/login"){
        if (data.code === 401){
            router.replace({
                path: '/login'
            })
        }
    }
    if (response.status === 404){
        router.push({
            name: '404错误页面'
        })
    }
    if (data.code === 404) {
        Vue.prototype.$message.error(data.info);
    }
    if (response.status === 304) {
        Vue.prototype.$message.error("服务器崩溃了~");
    }
    endLoading();
    return response;
},error => {

    endLoading();
    let response = error.response;
    if (response === undefined){
        Vue.prototype.$message.error("服务器崩溃了~");

        return;
    }
    let data = response.data;
    if (error.status === 401 || data.code === 401){
        Vue.prototype.$message.error(data.info);
        router.replace({
            path: '/login'
        })
    }else {
        router.push({
            name: '404错误页面'
        })
    }
});
new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');
